package com.siblings.loan.utils.dialog

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.Typeface
import android.net.Uri
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.siblings.lib_baseadapter.SIBOnItemChildClickListener
import com.siblings.lib_permission.OnPermissionCallback
import com.siblings.lib_permission.Permission
import com.siblings.lib_permission.XXPermissions
import com.siblings.loan.R
import com.siblings.loan.app.Apps
import com.siblings.loan.databinding.DialogKefuBinding
import com.siblings.loan.http.HttpHelper
import com.siblings.loan.ui.user.adapter.SibKefuAdapter
import com.siblings.loan.utils.event.SibEventType
import com.siblings.loan.utils.helper.SharedHelper
import org.json.JSONObject

/**
 * SiblingsLoan
 * @Author wwdeng
 * @CreateTime: 2024/7/15 10:29
 * @Annotation：联系客服Dialog
 */
class KefuDialog : ProDialog {
    lateinit var binding: DialogKefuBinding
    private var mCallback: IDialogCallback? = null
    //事件备注
    private var eventRemark = ""

    //客服联系方式列表
    private var kefuAdapter: SibKefuAdapter? = null
    override fun getRootView(): View {
        binding = DialogKefuBinding.inflate(LayoutInflater.from(context))
        return binding.root
    }

    constructor(context: Context?) : super(context) {}
    constructor(context: Context?, callback: IDialogCallback?) : super(context) {
        mCallback = callback
    }

    constructor(context: Context?, remark: String,callback: IDialogCallback?) : super(context) {
        mCallback = callback
        eventRemark = remark
    }

    override fun initWindow() {
        val params = window!!.attributes
        params.width =  WindowManager.LayoutParams.MATCH_PARENT
        params.height = WindowManager.LayoutParams.WRAP_CONTENT
        window!!.attributes = params
        window!!.setWindowAnimations(R.style.dialog_scale_anim) //修改动画样式
        window!!.setGravity(Gravity.CENTER)
    }

    override fun initView() {
        initSibRecyclerView()
    }

    override fun initListener() {
        setOnClickListener(R.id.imgClose)
    }

    override fun initData() {
        loadSibKefuContactListAction()
    }

    override fun onViewClick(v: View?) {
        dismiss()
    }

    /**
     * 初始化Tab列表
     */
    private fun initSibRecyclerView() {
        binding.recyclerView.layoutManager = LinearLayoutManager(context)
        kefuAdapter = SibKefuAdapter(binding.recyclerView)
        binding.recyclerView.adapter = kefuAdapter
        binding.recyclerView.itemAnimator = DefaultItemAnimator()
        kefuAdapter!!.setOnItemChildClickListener(SIBOnItemChildClickListener { _, childView, position ->
            val item = kefuAdapter!!.getItem(position)
            if (childView.id == R.id.btnFun) {//切换item
                when(item.optString("type")){
                    "MOBILE" -> {//电话
                        if (XXPermissions.isGranted(context, Permission.CALL_PHONE)){
                            onCallAction(item)
                        } else {
                            XXPermissions.with(context)
                                .permission(Permission.CALL_PHONE)
                                .request(object: OnPermissionCallback {
                                    override fun onGranted(p0: MutableList<String>, p1: Boolean) {
                                        HttpHelper.addSibEventAction(SibEventType.CLICK.SIB_CLICK_PERMISSION_SYSTEM_AGREE, Permission.CALL_PHONE)
                                        onCallAction(item)
                                    }
                                    override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                                        HttpHelper.addSibEventAction(SibEventType.CLICK.SIB_CLICK_PERMISSION_SYSTEM_DENY, Permission.CALL_PHONE)
                                        XXPermissions.startPermissionActivity(context, Permission.CALL_PHONE)
                                    }
                                })
                        }
                    }
                    else -> {//邮箱
                        onCopyAction(item)
                    }
                }
            }
        })
    }

    /**
     * 获取联系方式列表
     */
    private fun loadSibKefuContactListAction(){
        val data = JSONObject(SharedHelper.getSibSPString(SharedHelper.SIB_SPKEY.SIBLINGS_COMMON))
        val contactList = arrayListOf<JSONObject>()
        val customize = data.optJSONObject("customize")
        if (customize != null){
            val mobileList = customize.optString("mobile").split(",")
            for (i in mobileList.indices){
                val obj = JSONObject()
                obj.put("type","MOBILE")
                obj.put("value", mobileList[i])
                contactList.add(obj)
            }
            val emailList = customize.optString("email").split(",")
            for (i in emailList.indices){
                val obj = JSONObject()
                obj.put("type","EMAIL")
                obj.put("value", emailList[i])
                contactList.add(obj)
            }
        }
        kefuAdapter!!.data = contactList

        //工作时间
        val timeString = "\n${customize?.optString("workDate")},${customize?.optString("workTime")}"
        val showString = String.format(context.getString(R.string.dialog_kefu_work_time),timeString)
        val spString = SpannableString(showString)
        val start = showString.indexOf(timeString)
        val end = start + timeString.length
        spString.setSpan(ForegroundColorSpan(Color.parseColor("#FF08252C")), start, end, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
        // 创建一个StyleSpan对象，设置样式为Typeface.BOLD，即加粗
        val boldSpan = StyleSpan(Typeface.BOLD)
        spString.setSpan(boldSpan,start, end, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
        binding.textWorkTime.text = spString
    }

    /**
     * 复制
     */
    private fun onCopyAction(item: JSONObject){
        val type = item.optString("type")
        HttpHelper.addSibEventAction(SibEventType.CLICK.SIB_CLICK_USER_FEEDBACK_COPY,type + "：" + item.optString("value"))
        // 获取剪贴板管理器
        val clipboardManager = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        // 创建一个 ClipData 对象，将要复制的文本放入其中
        val clipData = ClipData.newPlainText("label", item.optString("value"))
        // 将 ClipData 对象放入剪贴板
        clipboardManager.setPrimaryClip(clipData)
        showToast(Apps.app.getString(R.string.dialog_kefu_copy_success))
    }

    /**
     * 拨号
     */
    private fun onCallAction(item: JSONObject){
        val type = item.optString("type")
        HttpHelper.addSibEventAction(SibEventType.CLICK.SIB_CLICK_USER_FEEDBACK_DIAL,type + "：" + item.optString("value"))
        val callIntent = Intent(Intent.ACTION_DIAL)
        callIntent.setData(Uri.parse("tel:${item.optString("value")}"))
        context.startActivity(callIntent)
    }

    interface IDialogCallback {
        //按钮点击
        fun onClick(view: View?)
    }

    override fun onStart() {
        super.onStart()
        HttpHelper.addSibEventAction(SibEventType.DIALOG.SIB_DIALOG_KEFU_SHOW,eventRemark)
    }

    override fun dismiss() {
        super.dismiss()
        HttpHelper.addSibEventAction(SibEventType.DIALOG.SIB_DIALOG_KEFU_DISMISS,eventRemark)
    }
}